package com.dc.service.impl;

import com.dc.FastdfsUtils;
import com.dc.common.ResponseResultVO;
import com.dc.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.dc.common.ResponseResultVO.checkParameterIsNotNull;
import static com.dc.common.ResponseResultVO.failResult;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Resource
    private FastdfsUtils fastdfsUtils;


    @Override
    public ResponseResultVO uploadFile(MultipartFile[] files) {
        List<String> urls = new ArrayList<>();
        if (files != null && files.length > 0) {
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    return failResult("MultipartFile不能为空!");
                }
                String fileUrl = null;
                try {
                    fileUrl = fastdfsUtils.upload(file);
                } catch (IOException e) {
                    log.error("上传fastDFS异常");
                }
                urls.add(fileUrl);
            }
        }
        return ResponseResultVO.successResult(urls);
    }

    @Override
    public void downloadFile(String path, String name, HttpServletResponse servletResponse) {
        try {
            fastdfsUtils.download(path, name, servletResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public ResponseResultVO deleteFile(String path) {
        checkParameterIsNotNull(path, "参数不能为空");
        fastdfsUtils.delete(path);
        return ResponseResultVO.successResult("删除成功");
    }

}
